<?php
require_once __DIR__ . '/__load.php';
// 下一个阶段，将基于当前类，进行扩展，注意将部分private设置为protected
class Download
{
    public $header; // Array  :  设置头部
    public $dir; // 设置图片存放目录
    public $pages; // 设置数量
    public $src; // 设置图片前缀
    public $title; // 设置标题
    public $real_dir; // 真实目录 dir / title 的 目录
    public $fork; // 子进程数量 --- TODO
    public $her_index; // 某个模特的写真作品首页

    public function __construct()
    {
        // 设置假 ip
        $fake_ip =
        Token::rand_str(2, 2) . '.' .
        Token::rand_str(2, 2) . '.' .
        Token::rand_str(2, 2) . '.' .
        Token::rand_str(2, 2);
        // 设置头部
        $this->header = [
            "Accept:image/webp,image/*,*/*;q=0.8",
            "Accept-Language:zh-CN,zh;q=0.8",
            "Connection:keep-alive",
            "Host:mtl.ttsqgs.com",
            "Referer:https://www.meitulu.com/item",
            "User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.wer.221 Safari/537.123 SE 2.X MetaSr 1.0",
            "X-Forwarded-For:" . $fake_ip,
        ];
        // 设置标题
        $this->title = '';
        // 设置目录
        $this->dir      = 'download/';
        $this->real_dir = '';
        // 设置子进程数量
        $this->fork = 0;
    }

    /**
     * 完成下载
     * @param String pic_pre  图片前缀 https://mtl.ttsqgs.com/images/img/8911/
     * @param String pre_suf  图片后缀 如， "jpg"
     * @param Number zero_num 左边补0的个数，如该值设为2， 则会将小于十的数，如，2 变成 002
     */
    // array  bool callable int float string iterable
    public function handle(string $pic_pre, string $pre_suf, int $zero_num = 1)
    {
        $this->set_dir();
        echo 'Download ...' . PHP_EOL;
        for ($i = 1; $i <= $this->pages; $i++) {
            $name = $this->set_zero($i, $zero_num) . '.' . $pre_suf;
            $src  = $pic_pre . $name;
            $path = $this->real_dir . '/' . $name;
            if (is_file($path)) {
                echo $src . ' --- exists' . PHP_EOL;
                continue;
            } else {
                echo $src . PHP_EOL;
            }
            $data = CurlRequest::run($src, null, $this->header);
            file_put_contents($path, $data);
        }

        echo 'One task is finished' . PHP_EOL;
    }

    // 获取某个妹子写真的作品数据 --- 目前不涉及分页
    public function get_data()
    {
        $header = [
            "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            "Accept-Encoding:gzip, deflate, sdch",
            "Accept-Language:zh-CN,zh;q=0.8",
            "Cache-Control:no-cache",
            "Cookie:UM_distinctid=1615a0d9fd2166-06355844e9b39b-1571466f-1fa400-1615a0d9fd316c; CNZZDATA1255487232=1958726030-1517653567-%7C1517653567; CNZZDATA1255357127=605834772-1517631364-https%253A%252F%252Fwww.baidu.com%252F%7C1517671118; Hm_lvt_1e2b00875d672f10b4eee3965366013f=1517634298; Hm_lpvt_1e2b00875d672f10b4eee3965366013f=1517672911",
            "Connection:keep-alive",
            "Host:www.meitulu.com",
            "Referer:https://www.meitulu.com/item",
            "User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.wer.221 Safari/537.123 SE 2.X MetaSr 1.0",
            "X-Forwarded-For:10.2.12.11",
        ];

        $temp = CurlRequest::run($this->her_index, null, $header);


        // 拉出有效数据
        $rule = '/<ul class="img">(.*?)\<\/ul>/is';
        $m    = array();
        preg_match($rule, $temp, $m);


        $list = $m[1]; // 保留本次所需的数据
        $m    = null; // 清空用不上的数据

        // 提取图片资源前缀信息
        $rule1       = "/src=\"(.*?)0.jpg\"/";
        $matches_src = array();
        preg_match_all($rule1, $list, $matches_src);


        // 提取专辑名
        $rule2         = "/alt=\"(.*?)\"/";
        $matches_title = array();
        preg_match_all($rule2, $list, $matches_title);

        // 提取图片总数
        $rule3         = "/图片： (.*?) 张/";
        $matches_pages = array();
        preg_match_all($rule3, $list, $matches_pages);

        // 将刚刚提取的数据 格式化打包到 json 中
        $count = count($matches_src[1]);
        $res   = [];
        for ($i = 0; $i < $count; $i++) {
            $res["src"][]   = $matches_src[1][$i];
            $res["title"][] = $matches_title[1][$i];
            $res["pages"][] = $matches_pages[1][$i];
        }
        // 合成数据;
        file_put_contents(__DIR__.'/../datas/data.json', json_encode($res, JSON_UNESCAPED_UNICODE));
        echo 'Got her index data ' . PHP_EOL;
    }

    // 设置目录
    protected function set_dir()
    {
        if ('' == $this->real_dir) {
            $this->real_dir = $this->dir . $this->title;
        }
        if (!is_dir(realpath($this->real_dir))) {
            echo 'Directory: createing ...' . PHP_EOL;
            mkdir($this->real_dir, 0777, true);
        } else {
            echo 'Directory: created' . PHP_EOL;
        }
    }

    // 对数字左边补零的个数
    protected function set_zero($num, $zero_num)
    {
        if (1 == $zero_num) {
            return $num;
        }
        $str = '';
        for ($i = 0; $i < zero_num; $i++) {
            $str .= '0';
        }

        if ($num < 10) {
            $num = $str . $num;
        }
        return $num;
    }
}
